package com.rainng.coursesystem.service;

import com.rainng.coursesystem.model.PaperItem;
import com.rainng.coursesystem.model.QuestionItem;
import com.rainng.coursesystem.repository.PaperRepository;
import com.rainng.coursesystem.repository.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class PaperService {

    @Autowired
    private PaperRepository paperRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private BaiduApiService baiduApiService;


    @Transactional
    public void createPaper(PaperItem paper) {
        for (QuestionItem question : paper.getQuestions()) {
            question.setPaper(paper); // 设置关联关系
            if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                Set<String> uniqueOptions = new LinkedHashSet<>(question.getOptions());
                question.setOptions(new ArrayList<>(uniqueOptions));
            }
        }
        System.out.println("Saving PaperItem: " + paper); // 打印要保存的 PaperItem 对象
        System.out.println("courseId: " + paper.getCourseId()); // 再次打印 courseId 的值

        paperRepository.save(paper);
    }



    @Transactional(readOnly = true)
    public List<PaperItem> listPapersByCourse(Long courseId) {
        return paperRepository.findByCourseId(courseId);
    }

    @Transactional
    public PaperItem getPaper(Integer paperId) {
        PaperItem paper = paperRepository.findPaperWithQuestions(paperId);
        if (paper != null) {
            for (QuestionItem question : paper.getQuestions()) {
                if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                    Collections.shuffle(question.getOptions()); // 随机化选项
                }
            }
        }
        return paper;
    }

    @Transactional
    public void deletePaper(Integer paperId) {
        paperRepository.deleteById(paperId);
    }

    public String markExam(String studentAnswer, Integer questionId) throws IOException {

        QuestionItem questionItem = questionRepository.findById(questionId)
                .orElseThrow(() -> new IllegalArgumentException("No question found with ID: " + questionId));
        List<String> answers = questionItem.getAnswer();
        String content=questionItem.getContent();
        String type = questionItem.getType();
        int maxscore=questionItem.getScore();
        String answer=answers.get(0);
        String score=baiduApiService.callApi("请直接告诉我应该得的分数，只回答数字，题目是"+content+ "标准答案是"+answer+"学生答案是"+studentAnswer+"最高分数是"+maxscore);
        return score;
    }
}
